/*
 * Copyright (C) 2018 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xdlinkdemo.device.resolver;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xuexiang
 * @since 2018/9/6 上午9:46
 */
public final class ResolverUtils {

    private ResolverUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 获取分包
     *
     * @param data
     * @return
     */
    public static List<byte[]> getSubPackage(byte[] data) {
        List<Integer> headIndex = new ArrayList<>(); //头索引
        List<Integer> endIndex = new ArrayList<>();  //尾索引

        for (int i = 0; i < data.length - 1; i++) {
            if (data[i] == (byte) 0x55 && data[i + 1] == (byte) 0xAA) {
                headIndex.add(i);
            } else if (data[i] == (byte) 0x00 && data[i + 1] == (byte) 0xFF) {
                endIndex.add(i);
            }
        }

        int size = Math.min(headIndex.size(), endIndex.size());
        if (size == 0) return null;

        List<byte[]> packages = new ArrayList<>();
        byte[] tmp;
        for (int i = 0; i < size; i++) {
            tmp = new byte[endIndex.get(i) - headIndex.get(i) + 2];
            System.arraycopy(data, headIndex.get(i), tmp, 0, tmp.length);
            packages.add(tmp);
        }
        return packages;
    }


}
